package com.ecube.maintenance.components.fragment;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.OrderAction;
import com.ecube.maintenance.biz.commons.ICCallBack;
import com.ecube.maintenance.biz.commons.ICTException;
import com.ecube.maintenance.components.widget.LoadingDialog;
import com.ecube.maintenance.pojos.OrderInfo;
import com.ecube.maintenance.pojos.ProductInfo;
import com.ecube.maintenance.pojos.SellerInfo;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;

import java.util.List;

public class OrderDetailFragment extends Fragment {
    public static final String ARG_ORDER_INFO = "orderinfo";
    ListView mTracerLayout;
    TracerListAdapter mTracerAdapter;
    TextView cancelOrder, orderPrice, orderNO, orderStatus,
            orderServiceTime, orderSpName, productName, productServices,
            userName, userMobile, userCar, arriveTime,driveMile;
    OrderInfo orderInfo;
    UserInfo userInfo;
    private View mDetailToggle;
    private View mTracerToggle;
    private View mDetailLayout;

    private int cancelStatus = 0;

    public OrderDetailFragment() {
    }

    public static OrderDetailFragment newInstance(OrderInfo info) {
        OrderDetailFragment fragment = new OrderDetailFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_ORDER_INFO, info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderInfo = (OrderInfo) getArguments().getSerializable(ARG_ORDER_INFO);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }
    private void configureActionBar() {
        ActionBar actionBar = getActivity().getActionBar();
        assert actionBar != null;
        View v = actionBar.getCustomView();
        if (v != null) {
            v.setVisibility(View.GONE);
        }
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("订单详情");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        String title = "订单详情";
        ActionBar ab = getActivity().getActionBar();
        assert ab != null;
        ab.setTitle(title);
        View rootView = inflater.inflate(R.layout.fragment_order_detail, container, false);
        mDetailToggle = rootView.findViewById(R.id.order_detail_toggle);
        mDetailLayout = rootView.findViewById(R.id.list_order_detail);
        mDetailToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDetailLayout.getVisibility() == View.GONE) {
                    setVisibilityOfDetail(true);
                    if (mTracerLayout.getVisibility() == View.VISIBLE) {
                        setVisibilityOfTracer(false);
                    }

                } else {
                    ((ViewGroup) mDetailToggle).getChildAt(1).setRotation(0);
                    mDetailLayout.setVisibility(View.GONE);
                }
            }
        });
        mTracerToggle = rootView.findViewById(R.id.order_tracer_toggle);
        mTracerLayout = (ListView) rootView.findViewById(R.id.list_order_tracer);
        mTracerToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTracerLayout.getVisibility() == View.GONE) {
                    /*((ViewGroup)mTracerToggle).getChildAt(1).setRotation(180);
                    mTracerLayout.setVisibility(View.VISIBLE);*/
                    setVisibilityOfTracer(true);
                    if (mDetailLayout.getVisibility() == View.VISIBLE)
                        setVisibilityOfDetail(false);
                } else {
                    /*((ViewGroup)mTracerToggle).getChildAt(1).setRotation(0);
                    mTracerLayout.setVisibility(View.GONE);*/
                    setVisibilityOfTracer(false);
                }
            }
        });
        mTracerAdapter = new TracerListAdapter(getActivity());
        mTracerLayout.setAdapter(mTracerAdapter);
        mTracerLayout.setOnItemClickListener(null);
        initView(rootView);
        fetchOrderDetail();
        return rootView;
    }

    void initView(View root) {
        orderNO = (TextView) root.findViewById(R.id.order_number);
        orderPrice = (TextView) root.findViewById(R.id.total_price);
        orderStatus = (TextView) root.findViewById(R.id.order_status);
        orderServiceTime = (TextView) root.findViewById(R.id.order_service_time);
        orderSpName = (TextView) root.findViewById(R.id.order_spname);
        userName = (TextView) root.findViewById(R.id.user_name);
        userCar = (TextView) root.findViewById(R.id.car_info);
        userMobile = (TextView) root.findViewById(R.id.user_mobile);
        cancelOrder = (TextView) root.findViewById(R.id.cancel_order);
        productName = (TextView) root.findViewById(R.id.order_product_name);
        productServices = (TextView) root.findViewById(R.id.order_product_service);
        arriveTime = (TextView) root.findViewById(R.id.order_arrive_time);
        driveMile = (TextView) root.findViewById(R.id.order_drive_mile);
        cancelOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cancelStatus == 0) {
                    cancelStatus++;
                    Bog.toast("再按一次以确认取消订单");
//                    cancelOrder.setBackgroundResource(R.color.ict_bg_dark);
                } else
                    cancelOrder();
            }
        });
    }

    void setViewData() {

        ProductInfo productInfo = orderInfo.getProductInfo();
        SellerInfo sellerInfo = orderInfo.getSpInfo();
        UserInfo owner = orderInfo.getCarOwnerInfo();
        if (productInfo != null) {
            orderServiceTime.setText(productInfo.getServiceDate() + " " + productInfo.getServiceStartTime()
                    + "~"
                    + productInfo.getServiceEndTime());
            orderPrice.setText("￥" + productInfo.getDiscountPrice());
            productName.setText(productInfo.getProductName());
            StringBuffer sb = new StringBuffer();
            int size = productInfo.getServiceItems() == null ? 0 : productInfo.getServiceItems().size();
            for (int i = 1; i <= size; i++) {
                sb.append(i + ". ").append(productInfo.getServiceItems().get(i - 1)).append("\n");
            }
            productServices.setText(sb);
        }
        if (sellerInfo != null) {
            orderSpName.setText(sellerInfo.getSpName());
        }
        if (owner != null) {
            userName.setText(owner.getRealName());
            userMobile.setText(owner.getMobile());
            userCar.setText(owner.getCarBrand() + "/"
                    + owner.getCarSerial() + "/"
                    + owner.getCarModel());
        }
        orderNO.setText(orderInfo.getOrderNO());
        orderStatus.setText(orderInfo.getOrderStatus());
        arriveTime.setText(orderInfo.getArriveTime());
        driveMile.setText(orderInfo.getDriveMile());
        if ("已取消".equals(orderInfo.getOrderStatus())) {
            cancelOrder.setVisibility(View.GONE);
        } else {
            cancelOrder.setVisibility(View.VISIBLE);
        }
        mTracerAdapter.refresh();
    }

    void fetchOrderDetail() {
        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.show();
        OrderAction.fetchOrderDetails(UserInfo.getInstance().getSid(),
                orderInfo.getOrderNO(), new ICCallBack<OrderInfo>() {
                    @Override
                    public void done(OrderInfo result, ICTException exception) {
                        dialog.getDialog().dismissDialogger();
                        if (exception == null) {
                            orderInfo = result;
                            if (orderInfo != null)
                                setViewData();
                        } else {
                            Bog.toast( exception.getMessage());
                        }

                    }
                });
    }

    void cancelOrder() {
        if ("已取消".equals(orderInfo.getOrderStatus())) {
            return;
        }
        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.show();
        OrderAction.cancelOrder(UserInfo.getInstance().getSid(),
                orderInfo.getOrderNO(), new ICCallBack<OrderInfo>() {
                    @Override
                    public void done(OrderInfo result, ICTException exception) {
                        dialog.getDialog().dismissDialogger();
                        if (exception == null) {
                            orderInfo = result;
                            if (orderInfo != null) {
                                orderInfo.setOrderStatus("已取消");
                                setViewData();
                            }
                        } else {
                            Bog.toast( exception.getMessage());
                        }
                    }
                });
    }

    private void setVisibilityOfTracer(boolean bool) {
        assert mTracerLayout != null && mTracerToggle != null;
        if (bool) {
            ((ViewGroup) mTracerToggle).getChildAt(1).setRotation(180);
            mTracerLayout.setVisibility(View.VISIBLE);
        } else {
            ((ViewGroup) mTracerToggle).getChildAt(1).setRotation(0);
            mTracerLayout.setVisibility(View.GONE);
        }
    }

    private void setVisibilityOfDetail(boolean bool) {
        assert mDetailLayout != null && mDetailToggle != null;
        if (bool) {
            ((ViewGroup) mDetailToggle).getChildAt(1).setRotation(180);
            mDetailLayout.setVisibility(View.VISIBLE);
        } else {
            ((ViewGroup) mDetailToggle).getChildAt(1).setRotation(0);
            mDetailLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private class TracerListAdapter extends BaseAdapter {
        LayoutInflater inflater;
        List<OrderInfo.OrderTimeLine> timeLines;

        TracerListAdapter(Context context) {
            this.inflater = LayoutInflater.from(context);
        }

        public void refresh() {
            if (orderInfo != null) {
                timeLines = orderInfo.getOrderTimeline();
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            return timeLines == null ? 0 : timeLines.size();
        }

        @Override
        public Object getItem(int position) {
            return timeLines.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = this.inflater.inflate(R.layout.item_list_order_tracer, null);
                holder.timeLineContent = (TextView) convertView.findViewById(R.id.timeline_content);
                holder.timeLineTime = (TextView) convertView.findViewById(R.id.timeline_time);
                holder.timeLinePoint = (ImageView) convertView.findViewById(R.id.timeline_point);
                holder.upperLine = convertView.findViewById(R.id.upper_line);
                holder.lowerLine = convertView.findViewById(R.id.lower_line);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            OrderInfo.OrderTimeLine line = timeLines.get(position);
            holder.timeLineContent.setText(line.getOrderAction());
            holder.timeLineTime.setText(line.getActionTime());
            //TODO 有更简洁的算法但暂时有BUG，故临时用这套.
            if (position == getCount() - 1 && position == 0) {
                holder.timeLinePoint.setImageResource(R.drawable.order_circle_current);
                holder.upperLine.setVisibility(View.INVISIBLE);
                holder.lowerLine.setVisibility(View.INVISIBLE);
                return convertView;
            }
            if (position == 0) {
                holder.timeLinePoint.setImageResource(R.drawable.order_circle_current);
                holder.upperLine.setVisibility(View.INVISIBLE);
                holder.lowerLine.setVisibility(View.VISIBLE);
                return convertView;
            }
            if (position == getCount() - 1) {
                holder.timeLinePoint.setImageResource(R.drawable.order_circle_normal);
                holder.lowerLine.setVisibility(View.INVISIBLE);
                holder.upperLine.setVisibility(View.VISIBLE);
                return convertView;
            }
            holder.timeLinePoint.setImageResource(R.drawable.order_circle_normal);
            holder.lowerLine.setVisibility(View.VISIBLE);
            holder.upperLine.setVisibility(View.VISIBLE);
//            convertView.setOnClickListener(new View.OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    getFragmentManager().beginTransaction()
//                            .add(OrderDetailFragment.newInstance(), "ODF")
//                            .addToBackStack("ODF").commit();
//                }
//            });
            return convertView;
        }

        public class ViewHolder {
            TextView timeLineContent, timeLineTime;
            ImageView timeLinePoint;
            View upperLine;
            View lowerLine;
        }
    }
}
